package com.xuanxing123.webapp.action.settings;

import com.opensymphony.xwork2.Preparable;
import com.xuanxing123.model.ProductType;
import com.xuanxing123.service.ProductTypeManager;
import com.xuanxing123.webapp.action.BaseAction;

import java.util.List;

public class ProductTypeAction extends BaseAction implements Preparable {
    private ProductTypeManager productTypeManager;
    private List productTypes;
    private ProductType productType;
    private Long id;
    private String query;

    public void setProductTypeManager(ProductTypeManager productTypeManager) {
        this.productTypeManager = productTypeManager;
    }

    public List getProductTypes() {
        return productTypes;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String productTypeId = getRequest().getParameter("productType.id");
            if (productTypeId != null && !productTypeId.equals("")) {
                productType = productTypeManager.get(new Long(productTypeId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        productTypes = productTypeManager.search(query, ProductType.class);
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public ProductType getProductType() {
        return productType;
    }

    public void setProductType(ProductType productType) {
        this.productType = productType;
    }

    public String delete() {
        productTypeManager.remove(productType.getId());
        saveMessage(getText("productType.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            productType = productTypeManager.get(id);
        } else {
            productType = new ProductType();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (productType.getId() == null);

        productTypeManager.save(productType);

        String key = (isNew) ? "productType.added" : "productType.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}